import React from 'react';
import { Button, Form, Input, message } from 'antd';
import './Zhuce1.css';
import imageSrc from '../../picture/yuanbiao.png';
import { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const tailFormItemLayout = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 16, offset: 8 },
  },
};

const Zhuce1 = () => {
  const nav = useNavigate();
  const [inputValue1, setInputValue1] = useState('');
  const [inputValue2, setInputValue2] = useState('');
  const [inputValue3, setInputValue3] = useState('');
  const handleChange1 = (event) => {
    setInputValue1(event.target.value);
  };
  const handleChange2 = (event) => {
    setInputValue2(event.target.value);
  };
  const handleChange3 = (event) => {
    setInputValue3(event.target.value);
  };

  const handleSubmit = (values) => {
    console.log('输入的值：', inputValue1, inputValue2, inputValue3);
    console.log('输入的值：', values);
    const postData = {
      user_name: values.nickname, // 假设昵称作为用户名  
      password: values.password,
      e_mail: values.email,
    };
    //axios.post('http://localhost/3001/own/debark', postData)
    axios({
      method: 'post',
      url: 'http://localhost:3001/own/register',
      data: postData,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded', // 修改 Content-Type
        //'Authorization': 'Bearer yourToken', // 添加授权头
      }
    })
      .then(response => {
        console.log(response.data);
        nav("/Denglu"); // 成功注册后跳转  
      })
      .catch(error => {
        console.error('There was an error!', error);
        message.error('注册失败，请检查输入的信息！');
      });

  };

  const validatePassword = (rule, value) => {  
    if (!value || value.length < 6) {  
      return Promise.reject(new Error('密码必须大于6位！'));  
    }  
  
    // 正则表达式检查字母、数字和特殊字符  
    const hasLetter = /[a-zA-Z]/.test(value);  
    const hasNumber = /[0-9]/.test(value);  
    const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value);  
    let hasTwoDifferentTypes = false;  
  
    // 确保密码包含至少两种不同类型的字符  
    if ((hasLetter && hasNumber) ||  
        (hasLetter && hasSpecialChar) ||  
        (hasNumber && hasSpecialChar)) {  
      hasTwoDifferentTypes = true;  
    }  
  
    if (!hasTwoDifferentTypes) {  
      return Promise.reject(new Error('密码至少应包含字母、数字和特殊字符中的两种！'));  
    }  
  
    return Promise.resolve();  
  };  


  const [form] = Form.useForm();
  // const onFinish = (values) => {
  //   console.log('Received values of form: ', values);
  // };
  return (
    <div className='zong'>
      <div className='title'>
        <img src={imageSrc} alt="Description of the image" className='image' />
        <div>
          <text className='title-text'>佳肴绘卷</text>
        </div>
      </div>
      <div className='register-zong'>
        <div className="register-box">
          <text className='b1'>新用户注册</text>
          <text className='b2' onClick={() => nav('/')}>已有帐号？直接登录</text>
          <div className='register-form'>
            <Form
              {...formItemLayout}
              form={form}
              name="register"
              onFinish={handleSubmit} // 注意这里直接使用 onFinish 而非包装在另一个函数中  
              style={{ maxWidth: 600 }}
              scrollToFirstError
            >
              <Form.Item
                name="email"
                rules={[
                  { type: 'email', message: '请输入正确的邮箱！' },
                  { required: true, message: '请输入你的邮箱', },
                ]}
              >
                <Input placeholder="请输入你的邮箱" className='email'
                  onChange={handleChange3} value={inputValue3} />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[
                  { required: true, message: '请输入你的密码' },
                  { validator: validatePassword }, // 添加自定义验证器  
                ]}
                hasFeedback
              >
                <Input.Password placeholder="请输入你的密码！" className='email' />
              </Form.Item>

              <Form.Item
                name="confirm"
                dependencies={['password']}
                hasFeedback
                rules={[
                  { required: true, message: '请输入相同的密码', },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次密码不匹配!'));
                    },
                  }),
                ]}
              >
                <Input.Password placeholder="请输入相同的密码！" className='email' />
              </Form.Item>

              <Form.Item
                name="nickname"
                rules={[{ required: true, whitespace: true, message: '请输入你的昵称', }]}
              >
                <Input placeholder="请输入你的昵称!" className='email'
                  onChange={handleChange1} value={inputValue1} />
              </Form.Item>

              <Form.Item {...tailFormItemLayout}>
                <Button type="primary" htmlType="submit">
                  注册
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Zhuce1;
